package com.ptma.controllers;

import java.io.File;
import java.io.Serializable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ptma.android.client.Apk;
import com.ptma.android.client.ApkReader;
import com.ptma.model.Application;
import com.ptma.model.Device;
import com.ptma.model.User;
import com.ptma.repository.GenericRepo;

@Controller
@RequestMapping(value = "/secure")
public class FileUploadController extends AbstractController {

	@Autowired
	private GenericRepo<User, Serializable> userService;
	@Autowired
	private GenericRepo<Application, Serializable> applicationService;

	@Autowired
	private GenericRepo<Device, Serializable> downloaderService;

	private CommonsMultipartFile file;

	@RequestMapping(value = "/saveFile.html", method = RequestMethod.POST)
	public ModelAndView saveFile(
			@ModelAttribute("uploadItem") UploadItem uploadItem, Model map,
			HttpServletResponse response, HttpServletRequest request) {

		// Authentication auth = SecurityContextHolder.getContext()
		// .getAuthentication();
		//
		// String userName = auth.getName();
		//
		// File file = new File("src/main/webapp/"
		// + PropertyFile.valueOf("user.userAps.name"));
		// file.mkdir();
		//
		// file = new File("src/main/webapp/"
		// + PropertyFile.valueOf("user.userAps.name")
		// + File.separator + userName + File.separator
		// + apk.getPackageName() + File.separator
		// + apk.getVersionName());
		// file.mkdirs();
		//
		// File parentDir = new File("src/main/webapp/"
		// + PropertyFile.valueOf("user.userAps.name")
		// + File.separator + userName + File.separator
		// + apk.getPackageName());
		// parentDir.mkdirs();
		// file = new File(parentDir, "icon.jpg");
		// // Write icon
		// FileOutputStream fos = new FileOutputStream(file);
		// fos.write(apk.getApkIcon());
		// fos.close();
		// parentDir = new File("src/main/webapp/"
		// + PropertyFile.valueOf("user.userAps.name")
		// + File.separator + userName + File.separator
		// + apk.getPackageName() + File.separator
		// + apk.getVersionName());
		// // Write Apk
		// file = new File(parentDir, "app.apk");
		// fos = new FileOutputStream(file);
		// fos.write(FileUploadController.this.file.getBytes());
		//
		// fos.close();
		//
		// Application application = applicationService
		// .getApplicationByUserAndNameSpace(userName,
		// apk.getPackageName());
		// if (null != application) {
		// mv = new ModelAndView(new RedirectView("devices.html"));
		// request.getSession().setAttribute("application", application);
		// ApplicationVersion appVersion = new ApplicationVersion();
		// ApplicationVersion.Pk versionPk = new ApplicationVersion.Pk(
		// application, apk.getVersionName());
		//
		// versionPk.setApplication(application);
		//
		// appVersion
		// .setVersionComment("Build #: " + apk.getVersionName());
		//
		// applicationService.saveOrUpdate(appVersion);
		// } else {
		// mv = new ModelAndView(new RedirectView("devices.html"));
		// Application appNew = new Application();
		// appNew.setApplicationName(apk.getApplicationLabel());
		// appNew.setNameSpace(apk.getPackageName());
		// appNew.setUser(userService.getUserByEmail(userName));
		// ApplicationVersion appVersion = new ApplicationVersion();
		//
		// // //////////////////////////Assigning Downloader Will be
		// // removed later///////////////////////////////
		// Downloader d = new Downloader();
		// d.setEmail("yahya.arshad@gmail.com");
		//
		// String email = SecurityContextHolder.getContext()
		// .getAuthentication().getName();
		// d.setUser(new User(email));
		// d.setDeviceId("356378042257121");
		// Downloader dbDownloader = downloaderService
		// .getDownloaderByEmailAndDeviceId(d);
		// appNew.getDownloaders().add(dbDownloader);
		//
		// // /////////////////////////////////////////////////////////
		//
		// ApplicationVersion.Pk versionPk = new ApplicationVersion.Pk(
		// appNew, apk.getVersionName());
		//
		// appVersion.setVersionPk(versionPk);
		//
		// appVersion
		// .setVersionComment("Build #: " + apk.getVersionName());
		// List<ApplicationVersion> appVersions = new
		// ArrayList<ApplicationVersion>();
		// appVersions.add(appVersion);
		// appNew.setAppVersions(appVersions);
		// applicationService.save(appNew);
		// request.getSession().setAttribute("application", appNew);

		return null;
	}

	@RequestMapping(value = "/createNew", method = RequestMethod.POST)
	public ModelAndView createApplication(
			@ModelAttribute("uploadItem") UploadItem uploadItem, Model map,
			HttpServletResponse response, HttpServletRequest request) {

		file = (CommonsMultipartFile) uploadItem.getFile();

		String strFilePath = file.getStorageDescription();
		int startIndex = strFilePath.indexOf("[") + 1;
		int lastIndex = strFilePath.lastIndexOf("]");
		String fileLoc = strFilePath.substring(startIndex, lastIndex).trim();
		ModelAndView mv = new ModelAndView(
				"redirect:/secure/create_application.html");

		try {
			ApkReader apkReader = new ApkReader();
			Apk apk = apkReader.getApk(new File(fileLoc));
			map.addAttribute("pkgName", apk.getPackageName());
			map.addAttribute("versionName", apk.getVersionName());
			map.addAttribute("versionCode", apk.getVersionCode());
			map.addAttribute("appName", apk.getApplicationLabel());
		} catch (Exception e) {
			e.printStackTrace();

		}

		return mv;
	}

	@RequestMapping(value = "/upload.html", method = RequestMethod.GET)
	public ModelAndView uploadVersion(
			@ModelAttribute("uploadItem") UploadItem uploadItem, Model map,
			HttpServletResponse response, HttpServletRequest request) {

		return new ModelAndView("secure/upload");

	}

}
